import { Form, Input, InputNumber, Popconfirm, Table, Typography } from 'antd';
import React, { useEffect, useState } from 'react';
import { apiStockLibraryGoodsEdit } from '@/request/storageManager/store.js'


const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `请输入${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const Warning = ({ dataSource, rowStoreId }) => {
  const [form] = Form.useForm();
  const [data, setData] = useState(dataSource);
  const [editingKey, setEditingKey] = useState('');
  const isEditing = (record) => record.key === editingKey;
  useEffect(() => {
    setData(dataSource)
    setEditingKey('')

  }, [dataSource])
  const edit = (record) => {
    form.setFieldsValue({
      libraryName: '',
      minCount: '',
      ...record,
    });
    setEditingKey(record.key);

  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        let res = await apiStockLibraryGoodsEdit({ 
          id: item.id ? item.id : '', 
          dataId: rowStoreId, 
          goodsSkuId: item.goodsSkuId, 
          goodsId: item.goodsId, 
          libraryId: item.libraryId, 
          minCount: row.minCount ,
          goodsSkuNo:item.goodsSkuNo
        })
        if (res.code === 0) {
          newData.splice(index, 1, { ...item, ...row });
          setData(newData);
          setEditingKey('');
        }

      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const columns = [
    {
      title: '仓库名称',
      dataIndex: 'libraryName',
      width: '60%',
      editable: false,
    },
    {
      title: '库存预警值',
      dataIndex: 'minCount',
      width: '20%',
      editable: true,
      render: (text) => {
        if (text == -1) {
          return '不限制'
        }
        return text
      }
    },

    {
      title: '操作',
      width: '20%',
      dataIndex: 'operation',
      render: (_, record) => {

        const editable = isEditing(record);
        return editable ? (
          <span>
            <Typography.Link
              onClick={() => save(record.key)}
              style={{
                marginRight: 8,
              }}
            >
              保存
            </Typography.Link>
            <a onClick={cancel}>取消</a>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
            编辑
          </Typography.Link>
        );
      },
    },
  ];
  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: 'number',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <Form form={form} component={false}>
      <Table
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        bordered
        dataSource={data}
        columns={mergedColumns}
        rowClassName="editable-row"
        pagination={false}
      />
    </Form>
  );
};
export default Warning